/**
 * JAVACC DEMO 1.0
 */
package com.apache.passport.common;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;

import java.io.*;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

/**
 * 根据IP查询地址,目前使用淘宝接口
 * http://ip.taobao.com/service/getIpInfo.php
 * description:
 *
 * @author Hou Dayu 创建时间：2016-5-15
 */
public class IPInfo {

    private static IPInfo instance;

    private IPInfo() {
    }

    public static IPInfo getInstance() {
        if (null == instance) {
            instance = new IPInfo();
        }
        return instance;
    }

    public String getIpInfo(String url, Map map) {
        String sb = "";
        HttpClient httpClient = new HttpClient();
        GetMethod getMethod = new GetMethod(url);
        try {
            if (map.size() > 0) {
                Set keys = map.keySet();
                NameValuePair[] nameValuePair = new NameValuePair[keys.size()];
                int i = 0;
                Iterator it = keys.iterator();
                while (it.hasNext()) {
                    String key = (String) it.next();
                    String value = (String) map.get(key);
                    nameValuePair[i] = new NameValuePair(key, value);
                    i++;
                }
                getMethod.setQueryString(nameValuePair);
                int status = httpClient.executeMethod(getMethod);
                if (HttpStatus.SC_OK == status) {
                    sb = inputStreamToString(getMethod.getResponseBodyAsStream());
                } else {
                    sb = "{\"code\":1,\"data\":\"请求异常!\"}";
                }
            } else {
                sb = "{\"code\":1,\"data\":\"参数为空!\"}";
            }
        } catch (HttpException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sb;
    }

    /**
     * description:  将数据流转换成成string
     *
     * @param is
     * @return
     */
    public String inputStreamToString(InputStream is) {
        BufferedReader reader = null;
        StringBuilder responseText = new StringBuilder();
        String readerText = null;
        try {
            reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            readerText = reader.readLine();
            while (readerText != null) {
                responseText.append(readerText);
                responseText.append(System.getProperty("line.separator"));
                readerText = reader.readLine();
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return responseText.toString();
    }
}
